<template>
  <view>
    <view class="container">
      <!-- 顶部余额信息 -->
      <view class="balance-card">
        <view class="balance-title">当前余额:</view>

        <view>
          <u-row customStyle="margin-bottom: 10px">
            <u-col span="8">
              <view class="demo-layout bg-purple-light">
                <view class="balance-amount"
                  >¥ {{ formData.balance }}
                  <span style="font-size: 14px">元</span></view
                >
              </view>
            </u-col>
            <u-col span="4">
              <view class="demo-layout bg-purple"
                ><u-button
                  type="primary"
                  size="small"
                  @tap="cx"
                  text="明细查询"
                ></u-button
              ></view>
              <view style="margin-bottom: 10rpx"></view>
              <view class="demo-layout bg-purple"
                ><u-button
                  type="success"
                  size="small"
                  @tap="handleReset"
                  text="重置查询"
                ></u-button
              ></view>
            </u-col>
          </u-row>
        </view>
      </view>

      <!-- 明细列表 -->
      <view class="record-list">
        <view class="section-title">收支明细</view>
        <u-empty
          mode="data"
          text="暂无数据"
          v-if="dataList.length == 0"
          margin="15vh"
          :icon="getResource('img/phone/mini/no_data.png')"
        />
        <!-- <view v-if="records.length === 0" class="empty-tip">
				<text>暂无收支记录</text>
			</view> -->

        <scroll-view
          class="query_content"
          @scrolltolower="buttonScrolltolower"
          scroll-y="true"
          style="height: calc(100vh - 350rpx)"
          v-else
        >
          <view
            v-for="(item, index) in dataList"
            :key="index"
            class="record-item"
          >
            <view class="record-left">
              <view class="record-type">{{ item.balance_type_2_name }}</view>
              <view class="record-time">{{ item.created_at }}</view>
            </view>
            <view
              class="record-right"
              :class="{
                income: item.direction == '+',
                expense: item.direction == '-',
              }"
            >
              {{ item.direction }}{{ item.num }} 元
            </view>
            <!-- <view class="record-right" v-if="item.direction == '+'">
            + {{ item.num }} 元
          </view>

          <view class="record-" v-if="item.direction == '-'">
            - {{ item.num }} 元
          </view> -->
            <view class="record-balance">
              ¥ 之前余额：{{ item.from }}元 最新余额 {{ item.to }}元
            </view>
          </view>
        </scroll-view>
      </view>
    </view>

    <u-popup :show="show" @close="show = false" mode="center" :round="10">
      <view class="search-popup">
        <!-- 标题 -->
        <view class="search-header">
          <text class="title">筛选条件</text>
          <u-icon name="close" size="20" @click="show = false"></u-icon>
        </view>

        <!-- 交易类型 -->
        <view class="search-item">
          <text class="label">交易类型</text>
          <u-radio-group v-model="formData.balance_type_2" placement="row">
            <!-- <u-radio :customStyle="{marginRight: '20px'}" label="全部" name="all"></u-radio> -->
            <!-- <u-radio :customStyle="{marginRight: '20px'}" label="充值" name="101"></u-radio> -->

            <u-radio
              v-for="(item, index) in listtype"
              :key="index"
              :customStyle="{ marginRight: '20px' }"
              :label="item.name"
              :name="item.id"
            ></u-radio>
          </u-radio-group>
        </view>

        <!-- 日期区间 -->
        <view class="search-item">
          <text class="label">日期区间</text>
          <view class="date-range">
            <view
              @click="showStartDatePicker = true"
              style="
                border: 1px solid #dadbde;
                padding: 10px;
                border-radius: 5px;
                min-width: 230rpx;
                display: flex;
                justify-content: space-between;
              "
            >
              <view>
                {{ formData.startDate ? formData.startDate : "开始日期" }}
              </view>
              <u-icon name="calendar"></u-icon>
            </view>
            <!-- <u-input
              v-model="formData.startDate"
              placeholder="开始日期"
              @click="
                () => {
                  showStartDatePicker = true;
                  console.log(
                    '开始日期点击，showStartDatePicker:',
                    showStartDatePicker.value
                  );
                }
              "
              suffixIcon="calendar"
            ></u-input> -->
            <text class="date-separator">至</text>
            <view
              @click="showEndDatePicker = true"
              style="
                border: 1px solid #dadbde;
                padding: 10px;
                border-radius: 5px;
                min-width: 230rpx;
                display: flex;
                justify-content: space-between;
              "
            >
              <view>
                {{ formData.endDate ? formData.endDate : "结束日期" }}
              </view>
              <u-icon name="calendar"></u-icon>
            </view>
            <!-- <u-input
              v-model="formData.endDate"
              placeholder="结束日期"
              @click="showEndDatePicker = true"
              suffixIcon="calendar"
              readonly
            ></u-input> -->
          </view>
        </view>

        <!-- 搜索按钮 -->
        <view class="search-footer">
          <u-button type="primary" shape="circle" @click="handleSearch"
            >搜索</u-button
          >
          <u-button type="info" shape="circle" plain @click="handleReset"
            >重置</u-button
          >
        </view>

        <!-- 日期选择器 -->
        <u-datetime-picker
          :show="showStartDatePicker"
          v-model="startDateValue"
          mode="date"
          @confirm="confirmStartDate"
          @cancel="showStartDatePicker = false"
        ></u-datetime-picker>
        <u-datetime-picker
          :show="showEndDatePicker"
          v-model="endDateValue"
          mode="date"
          @confirm="confirmEndDate"
          @cancel="showEndDatePicker = false"
        ></u-datetime-picker>
      </view>
    </u-popup>
  </view>

  <!-- <view class="containerbb">
    <view class="bottom-view">
      <u-pagination
        :total="pages.page_total"
        :page-size="pages.page_size"
        @change="pageChange"
      ></u-pagination>
    </view>
  </view> -->
</template>

<script setup>
import {
  ref,
  onMounted,
  getCurrentInstance,
  computed,
  reactive,
  toRefs,
} from "vue";
import { getResource } from "../../utils/Resource";
import { showLoading, showToast } from "../../utils/toast";
const { proxy } = getCurrentInstance();
import { onShow } from "@dcloudio/uni-app";
import { getIntegralInfo } from "../../api/userInfo";
const show = ref(false);

const cx = () => {
  show.value = true;
};
onShow(() => {
  init();
});
// 当前余额
const balance = ref(1286.5);
const navbarHeight = ref(100);
// 收支记录
const records = ref([]);

// const form = ref({
// 	type: '',
// 	startDate: '',
// 	endDate: ''
// })

const pages = ref({
  page_size: 8,
  page_no: 1,
  page_total: 0,
  startDate: "",
  endDate: "",
  balance_type_2: "",
});

const pageChange = (e) => {
  console.log(e);
  pages.value.page_no = e;
  console.log(pages.value);
  select();
};

const data = reactive({
  formData: {
    count: 7,
    page_no: 1,
    page_size: 10,
    page_count: 1,
    balance_type: 1,
  },
  dataList: [],
  ji_fen: "",
  //   Parameters: { balance_type: "2" },
});
const ji_fen = ref("");
const { formData, dataList } = toRefs(data);
const init = async () => {
  return await getIntegralInfo(formData.value).then((res) => {
    console.log("init " + JSON.stringify(res.data));
    dataList.value = [...dataList.value, ...res.data.list];
    formData.value.balance = res.data.balance;
    formData.value.count = res.data.count;
    formData.value.page_count = res.data.page_count;
    formData.value.page_no = res.data.page_no;
    formData.value.page_size = res.data.page_size;
    ji_fen.value = res.data.ji_fen;
  });
};

const buttonScrolltolower = async () => {
  if (formData.value.count != dataList.value.length) {
    formData.value.page_no++;
    showLoading("加载中");
    await init();
  } else {
    showToast("已经最后一页了~");
  }
};

const select = () => {
  //   proxy
  //     .$http({
  //       url: "WechatUserBalance/index?Balancetype=1",
  //       data: pages.value,
  //     })
  //     .then((r) => {
  //       console.log(r);
  //       //   records.value = r.data.data.list;
  //       //   balance.value = r.data.data.balance;
  //       //   pages.value.page_total = r.data.data.count;
  //       // 计算当前余额（假设records是按时间倒序排列的）
  //     });
};

// 加载数据

const showStartDatePicker = ref(false);
const showEndDatePicker = ref(false);
const startDateValue = ref(Date.now());
const endDateValue = ref(Date.now());

// const open = () => {
// 	show.value = true
// 	emit('open')
// }

// const close = () => {
// 	show.value = false
// 	emit('close')
// }

const confirmStartDate = (e) => {
  formData.value.startDate = uni.$u.timeFormat(e.value, "yyyy-mm-dd");
  showStartDatePicker.value = false;
};

const confirmEndDate = (e) => {
  formData.value.endDate = uni.$u.timeFormat(e.value, "yyyy-mm-dd");
  showEndDatePicker.value = false;
};

const handleSearch = async () => {
  dataList.value = [];
  formData.value.page_no = 1;
  console.log("搜索条件:", formData.value);
  // emit('search', form.value)
  // close()
  //   select();
  await init();
  show.value = false;
};

const handleReset = async () => {
  dataList.value = [];
  formData.value = {};
  await init();
  show.value = false;
};

const listtype = ref();

// 获取查询分类
const indexType = () => {
  proxy
    .$http({
      url: "WechatUserBalance/indexType?balance_type=1",
    })
    .then((r) => {
      console.log(r);
      listtype.value = r.data.data;
    });
};

onMounted(() => {
  select();
  indexType();
});
</script>

<style lang="scss" scoped>
:deep(.u-empty) {
  margin: 15vh !important;
}
.container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.balance-card {
  background: linear-gradient(135deg, #4a6cf7, #2546f0);
  border-radius: 16rpx;
  padding: 40rpx 30rpx;
  color: #fff;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(74, 108, 247, 0.2);

  .balance-title {
    font-size: 28rpx;
    margin-bottom: 10rpx;
  }

  .balance-amount {
    font-size: 56rpx;
    font-weight: bold;
  }
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin: 30rpx 0 20rpx 0;
  padding-left: 20rpx;
}

.record-list {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.record-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
  position: relative;

  &:last-child {
    border-bottom: none;
  }

  .record-left {
    flex: 1;
  }

  .record-type {
    font-size: 32rpx;
    color: #333;
    margin-bottom: 10rpx;
  }

  .record-time {
    font-size: 24rpx;
    color: #999;
  }

  .record-right {
    font-size: 36rpx;
    font-weight: bold;
    margin-right: 30rpx;
    &.income {
      color: #4a6cf7;
    }

    &.expense {
      color: #ff4d4f;
    }
  }
  //   .record-right {
  //     font-size: 36rpx;
  //     font-weight: bold;
  //     margin-right: 30rpx;
  //     color: #4a6cf7;
  //   }

  //   .record- {
  //     font-size: 36rpx;
  //     font-weight: bold;
  //     margin-right: 30rpx;
  //     color: #f72124;
  //   }

  .record-balance {
    font-size: 18rpx;
    color: #b4b4b4;
    position: absolute;
    right: 20rpx;
    bottom: 15rpx;
    margin-top: 30rpx;
  }
}

.empty-tip {
  text-align: center;
  padding: 60rpx 0;
  color: #999;
  font-size: 28rpx;
}

.containerbb {
  width: 80vw;
}

.search-popup {
  width: 600rpx;
  padding: 30rpx;
  background-color: #fff;
  border-radius: 16rpx;
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.search-item {
  margin-bottom: 40rpx;
}

.label {
  display: block;
  margin-bottom: 20rpx;
  font-size: 28rpx;
  color: #666;
}

.date-range {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.date-separator {
  margin: 0 20rpx;
  color: #999;
}

.search-footer {
  display: flex;
  justify-content: space-between;
  margin-top: 50rpx;
}

.search-footer button {
  flex: 1;
  margin: 0 10rpx;
}
</style>
